
def handleCustomApply(customObjApply, customNames0=[], type='dx', tblAbbr='dx'):
    customNames = customNames0

    # 从customObjApply中获取 custom_apply，并且转换为sql文字
    customCodes = [custom.get('j_code') for custom in customObjApply if custom.get('j_code')]

    # isComma = any(
    #     ',' in (custom.get('names') or '') or
    #     ',' in (custom.get('med_codes') or '') or
    #     ',' in (custom.get('hsp_codes') or '') or
    #     ',' in (custom.get('hsp_names') or '')
    #     for custom in customObjApply
    # )
    # if not isComma:
        # customNames = []
    # 不管怎么样，再也不需要 customNames 了
    customNames = []
    
    # 处理 customCodes 的 in 条件语句，考虑 in 1000 限制
    customCodesSql = ""
    if customCodes:
        batch_size = 1000
        batches = [customCodes[i:i+batch_size] for i in range(0, len(customCodes), batch_size)]
        custom_conditions = []
        for batch in batches:
            codes_str = ",".join(f"'{code}'" for code in batch)
            if type == 'dx':
                custom_conditions.append(f"{tblAbbr}.dx_code IN ({codes_str})")
            elif type == 'tx':
                custom_conditions.append(f"{tblAbbr}.tx_code IN ({codes_str})")
            elif type == 'sie':
                custom_conditions.append(f"{tblAbbr}.icd_code IN ({codes_str})")
            elif type == 'item':
                custom_conditions.append(f"{tblAbbr}.item_j_code IN ({codes_str})")
            else:
                raise ValueError(f"Unsupported type: {type}")
        customCodesSql = "AND (" + " OR ".join(custom_conditions) + ")\n"

    # 处理 customNames 的 like 条件
    # 250729_155200_ 太耗性能了，不再 like 了
    customNamesSql = ""
    # if customNames:
    #     if type == 'dx' and tblAbbr != 'sicd':
    #         like_fields = [
    #             f'{tblAbbr}.dx_code',
    #             f'{tblAbbr}.dx_name',
    #             f'{tblAbbr}.dx_hsp_name',
    #         ]
    #     elif type in ('dx', 'tx') and tblAbbr == 'sie':
    #         like_fields = [
    #             f'{tblAbbr}.icd_code',
    #             f'{tblAbbr}.icd_names',
    #             f'{tblAbbr}.icd_hsp_names',
    #         ]
    #     elif type == 'item' and tblAbbr != 'sie':
    #         like_fields = [
    #             f'{tblAbbr}.item_code',
    #             f'{tblAbbr}.item_name',
    #             f'{tblAbbr}.item_med_code',
    #             f'{tblAbbr}.item_hsp_code',
    #             f'{tblAbbr}.item_hsp_name'
    #         ]
    #     elif type == 'item' and tblAbbr == 'sie':
    #         like_fields = [
    #             f'{tblAbbr}.item_code',
    #             f'{tblAbbr}.item_names',
    #             f'{tblAbbr}.item_med_codes',
    #             f'{tblAbbr}.item_hsp_codes',
    #             f'{tblAbbr}.item_hsp_names'
    #         ]
    #     # 分离精确匹配（没有%）和模糊匹配（有%）的name
    #     exact_names = [name for name in customNames if '%' not in name and not name.startswith('__') and not name.endswith('__')]
    #     fuzzy_names = [name for name in customNames if '%' in name and not name.startswith('__') and not name.endswith('__')]
        
    #     name_conditions = []
        
    #     # 处理精确匹配：生成 IN 语句，考虑1000限制
    #     if exact_names:
    #         batch_size = 1000
    #         for field in like_fields:
    #             batches = [exact_names[i:i+batch_size] for i in range(0, len(exact_names), batch_size)]
    #             for batch in batches:
    #                 names_str = ",".join(f"'{name}'" for name in batch)
    #                 name_conditions.append(f"{field} IN ({names_str})")
        
    #     # 处理模糊匹配：生成 LIKE 语句
    #     if fuzzy_names:
    #         like_conds = []
    #         for name in fuzzy_names:
    #             like_conds.extend(f"{field} LIKE '{name}'" for field in like_fields)
    #         name_conditions.extend(like_conds)
        
    #     customNamesSql = "AND (" + " OR ".join(name_conditions) + ")\n" if name_conditions else ""

    return customCodesSql, customNamesSql

def handleValueApply(filterDatum, type='dx', tblAbbr='dx'):
    # 获得value_apply，值是一个列表，里面的code是编码；另外value是name的列表
    valueObjApply = filterDatum['value_apply']
    valueNames = filterDatum['value']

    valueCodesSql, valueNamesSql = handleCustomApply(valueObjApply, valueNames, type, tblAbbr)

    return valueCodesSql, valueNamesSql

def handleTriggerApply(ruleAct):
    # 从ruleAct中获取 trigger_apply，并且转换为sql文字
    triggerObjApply = ruleAct.get('trigger_apply', [])
    triggerNames = ruleAct['trigger']
    
    triggerCodesSql, triggerNamesSql = handleCustomApply(triggerObjApply, triggerNames, type='item', tblAbbr='d')

    return triggerCodesSql, triggerNamesSql
